import tornado.ioloop
import tornado.web
import peewee_async
# 导入基础类
from base import BaseHandler

# 导入数据库操作类
from db import database

# 导入用户模块
import user
import sub
# import baidu
# import img
import ks

import os

import aioredis  # 异步的redis
import asyncio

import redis

from tornado.options import define, options
define('port', default=8000, help='default port',type=int)

# 设置tornado静态文件夹目录
static_path = os.path.join(os.path.dirname(__file__),"static")

class TestHandler(BaseHandler):

	async def get(self):

		return self.finish({"msg":"hello Tornado"})

# 集成路由
urlpatterns = [(r'/',TestHandler)]
urlpatterns += user.urlpatterns + sub.urlpatterns + ks.urlpatterns
# urlpatterns += baidu.urlpatterns
# urlpatterns += img.urlpatterns


app = tornado.web.Application(

	handlers=urlpatterns,static_path=static_path,debug=True
)

# 将数据库链接注入到事件循环中
app.objects = peewee_async.Manager(database)
# 将redis链接注入到事件循环
app.redis = redis.Redis(decode_responses=True)   # decode_responses=True 自动解码

# # 将异步redis链接注入到事件循环
# async def redis_pool(loop):
# 	return await aioredis.create_redis_pool('localhost',minsize=1,
# 											maxsize=1000,encoding='utf8',loop=loop)
# loop = asyncio.get_event_loop()
# app.redis = loop.run_until_complete(redis_pool(loop))

if __name__ == "__main__":
	print("开启服务")
	tornado.options.parse_command_line()
	app.listen(options.port)
	tornado.ioloop.IOLoop.instance().start()
